const express = require('express');
const route = express.Router();
const pool = require('../pool');
route.post("/add", (req, res) => {
  var obj = req.body;
  if (!obj.uid) {
    res.json({ code: 301, msg: "uid is required" });
    return;
  }
  if (!obj.cid) {
    res.json({ code: 302, msg: "cid is required" });
    return;
  }
  if (!obj.count) {
    obj.count = 1;
  }
  // 先查询用户的购物车中是否已经添加过该商品?
  let sql = "select count(*) as num from cart where userId=? And courseId=?";
  pool.query(sql, [obj.uid, obj.cid], (err, result) => {
    if (err) throw err;
    if (result[0].num > 0) {
      // 说明商品已存在,更新购物车数量
      var sql = `update cart set count=count+${obj.count} where userId=${obj.uid} and courseId=${obj.cid}`;
    } else {
      // 说明商品未存在,直接添加商品
      // 插入购物车表
      var sql = `insert into cart values (null,${obj.uid},${obj.cid},${obj.count})`
    }
    pool.query(sql, (err, result) => {
      res.json({ data: result })
    })
  })


})
route.post("/list", (req, res) => {
  let obj = req.body;
  if (!obj.uid) {
    return res.json({ code: 301, msg: "uid is required" })
  }
  let sql = "SELECT course.title,course.price,course.pic,cart.courseId,cart.count,cart.ctid FROM course,cart WHERE course.cid=cart.courseId AND cart.userId=" + obj.uid;
  pool.query(sql, [obj.uid], (err, result) => {
    if (err) throw err;
    if (result.length > 0) {
      console.log(result);
      res.json({ code: 200, msg: "success", data: result })
    } else {
      res.json({ code: 201, msg: "cart empty", data: result })
    }
  })
})
// 更新购物车
route.post("/update", (req, res) => {
  let obj = req.body;
  console.log(obj);
  let sql = `update cart set count=count+${obj.count} where userId=${obj.uid} and ctid=${obj.ctid}`;

  pool.query(sql,(err,result)=>{
    if(err) throw err;
    if(result.affectedRows>0){
      res.json({code:200,msg:"success"})
    }else{
      res.json({code:400,msg:"change fail"})
    }
  })

})
// 清空购物车
route.post("/empty",(req,res)=>{
  let obj=req.body;
  let sql="delete from cart where userId=?"
  pool.query(sql,[obj.uid],(err,result)=>{
    if(err)throw err;
    if(result.affectedRows>0){
      res.json({code:200,msg:"empty success"});
    }else{
      res.json({code:401,msg:"empty fail"});
    }
  })
})
// 删除单个商品
route.post("/delete",(req,res)=>{
  let obj=req.body;
  console.log(obj);
  let sql="delete from cart where ctid=?";
  pool.query(sql,[obj.ctid],(err,result)=>{
    if(err)throw err;
    if(result.affectedRows>0){
      res.json({code:200,msg:"delete success"});
    }else{
      res.json({code:401,msg:"delete fail"});
    }
  })
})
module.exports = route;